package com.wan37.logic.chat.handler;

import com.wan37.logic.chat.cache.ChatCache;
import com.wan37.logic.chat.service.WorldChatService;
import com.wan37.logic.chat.util.ChatRouteUtil;
import com.wan37.logic.chat.domain.vo.ChatVO;
import com.wan37.logic.component.Worker;
import com.wan37.logic.db.AsynDBManager;
import com.wan37.logic.domain.vo.MessageVO;
import com.wan37.logic.global.reference.SpringContextHolder;
import com.wan37.logic.handler.MsgHandler;
import com.wan37.protobuf.constant.PtoNum;
import com.wan37.protobuf.message.client2server.game.GameChat;

/**
 * 世界聊天消息处理器
 *
 * @author : luoyong
 * @date : 2020-07-15 11:10
 **/
public class CGameWorldPlayerChatHandler extends MsgHandler {
    private ChatRouteUtil chatRouteUtil;
    private ChatCache chatCache;
    private AsynDBManager asynDBManager;
    private WorldChatService worldChatService;

    /**
     * MsgHandler构造函数
     *
     * @param messageVO
     */
    public CGameWorldPlayerChatHandler(MessageVO messageVO) {
        super(messageVO);
        this.chatRouteUtil = SpringContextHolder.getBean("chatRouteUtil");
        this.chatCache = SpringContextHolder.getBean("chatCache");
        this.asynDBManager = SpringContextHolder.getBean("asynDBManager");
        this.worldChatService = SpringContextHolder.getBean("worldChatService");
    }

    @Override
    public void execute(Worker worker) throws Exception {
        GameChat.WorldPlayerChat worldPlayerChat = (GameChat.WorldPlayerChat) messageVO.getMessage();
        ChatVO chatVO = new ChatVO(worldPlayerChat.getSenderId(), worldPlayerChat.getContent());
        chatCache.getWorldChatVOList().add(chatVO);
        asynDBManager.distributeWork(messageVO.getUserId(), () -> worldChatService.save(chatVO));
        chatRouteUtil.sendWorldPlayerChatBroadcast(PtoNum.WORLDPLAYERCHAT, messageVO.getUserId(), chatVO);
    }
}
